package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Favorite;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.service.FavoriteService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 收藏管理控制器
 */
@RestController
@RequestMapping("/favorite")
public class FavoriteController {
    
    @Autowired
    private FavoriteService favoriteService;
    
    /**
     * 添加收藏
     */
    @PostMapping("/add")
    public Result<String> addFavorite(@RequestParam Long productId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        String message = favoriteService.addFavorite(userId, productId);
        return Result.success(message);
    }
    
    /**
     * 取消收藏
     */
    @DeleteMapping("/remove")
    public Result<String> removeFavorite(@RequestParam Long productId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        String message = favoriteService.removeFavorite(userId, productId);
        return Result.success(message);
    }
    
    /**
     * 查询我的收藏列表
     */
    @GetMapping("/myFavorites")
    public Result<List<Favorite>> getMyFavorites() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        List<Favorite> favorites = favoriteService.selectByUserId(userId);
        return Result.success(favorites);
    }
    
    /**
     * 检查是否已收藏
     */
    @GetMapping("/check/{productId}")
    public Result<Boolean> checkFavorite(@PathVariable Long productId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.success(false);
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        boolean isFavorite = favoriteService.checkFavorite(userId, productId);
        return Result.success(isFavorite);
    }
    
    /**
     * 查询商品的收藏数量
     */
    @GetMapping("/count/{productId}")
    public Result<Integer> getFavoriteCount(@PathVariable Long productId) {
        int count = favoriteService.countByProductId(productId);
        return Result.success(count);
    }
}

